//
//  StudentListViewController.m
//  PCSchool
//
//  Created by Arindam Ghosh on 7/12/13.
//  Copyright (c) 2013 Jayanta. All rights reserved.
//

#import "StudentListViewController.h"

@interface StudentListViewController ()

@end

@implementation StudentListViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    NSLog(@"SDD");
    // Do any additional setup after loading the view from its nib.
}

-(void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSLog(@"%@",NSStringFromClass(self.class));
    
    [self createLoadingView];
    [self.appDelegate.dataModel sendRequestFor:CLOSEST_STUDENT_DETAILS from:self];

    
    
    self.studentArray = [NSMutableArray array];
    
    self.studentDetailsArray4Leftpart = [[NSMutableArray alloc] initWithObjects:@"SurName",
                                         @"KnownAsName",
                                         @"Email",
                                         @"Home Teacher",
                                         @"Home Room",
                                         @"House",
                                         @"Dean",
                                         @"StudentAlert", nil];
    
    self.studentDetailsDictionary = [NSMutableDictionary dictionary];

    

    self.rightPanelTableView.scrollEnabled = NO;
    
    self.rightPanelStudentImageView.layer.cornerRadius = 4.0;
    self.rightPanelStudentImageView.layer.borderWidth = 1.0;
    self.rightPanelStudentImageView.layer.borderColor = [UIColor darkGrayColor].CGColor;
    
    self.rightPanelStudentImageView.contentMode = UIViewContentModeScaleAspectFit;
    self.rightPanelGraphView.contentMode = UIViewContentModeScaleAspectFit;
    
    
}

- (void)viewDidAppear:(BOOL)animated {
    
    @try {
        
        NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:0];
        [self.leftPanelTableView selectRowAtIndexPath:indexPath animated:YES  scrollPosition:UITableViewScrollPositionBottom];
    }
    @catch (NSException *exception) {
        NSLog(@"EXC %@",exception);
    }
    @finally {
        
    }
   
}


#pragma mark - TableView Delegates & Datasource

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 101) {
        
        return 46.0;
    }
    if (tableView.tag == 102) {
        
        return 50.0;
    }
    return 0.0;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 101) {
        
        [self setStudentData];
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView.tag == 101) {
        return [self.studentArray count];

    }
    if (tableView.tag == 102) {
        return [self.studentDetailsArray4Leftpart count];
        
    }
    return 0;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 101) {
        
        static NSString *CellIdentifier = @"StudenListCell";
        StudenListCell * cell =(StudenListCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        
        if (!cell) {
            
            cell =(StudenListCell*)[BaseTableCell cellFromNibNamed:CellIdentifier];
            
        }
        
        [self configureCell:cell atIndexPath:indexPath];
        
        return cell;
    }
    if (tableView.tag == 102) {
        
        static NSString *CellIdentifier = @"StudentDetailsCell";
        StudentDetailsCell * cell =(StudentDetailsCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        
        if (!cell) {
            
            cell =(StudentDetailsCell*)[BaseTableCell cellFromNibNamed:CellIdentifier];
            
        }
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        [self configureCell2:cell atIndexPath:indexPath];
        
        return cell;
    }
    
    return nil;
    
}

-(void)configureCell:(StudenListCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    cell.cellTextLabel.text = [self.studentArray objectAtIndex:indexPath.row];
    //cell.detailTextLabel.text=[[self.appDelegate.closestStudentDetails objectAtIndex:0] valueForKey:@"UDID"];
    [cell.personImageView setImageWithURL:[NSURL URLWithString:[[NSString stringWithFormat:@"%@Students/GetStudentImageByName/%@",BASE_URL,[self.appDelegate.arrayForStudentDetails valueForKey:@"MemberCode"]] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] placeholderImage:[UIImage imageNamed:@"no-imageBig.png"]];
}

-(void)configureCell2:(StudentDetailsCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    cell.leftLabel.text = [self.studentDetailsArray4Leftpart objectAtIndex:indexPath.row];
    cell.rightLabel.text = [self.studentDetailsDictionary valueForKey:cell.leftLabel.text];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

#pragma mark postData
-(id)postData
{
    NSLog(@"%@",self.appDelegate.arrayForStudentDetails);
	NSMutableDictionary *aDict=[NSMutableDictionary dictionary];
    [aDict setValue:[self.appDelegate.arrayForStudentDetails valueForKey:@"MemberId"] forKey:UPDATED_USERID];
    [aDict setValue:[self.appDelegate.arrayForStudentDetails valueForKey:@"MemberCode"] forKey:MEMBER_CODE];

    return aDict;
}

-(void) notifyRequesterWithData:(id)aManager
{
    [self removeLoadingView];
    
    ConnectionManager* aCon = aManager;
    NSLog(@"RESPONSE DATA  %@",aCon.responseString);
    
    if ([aCon.aRequest error])
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Message" message:[[aCon.aRequest error] localizedDescription] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
    }
    
    else
    {
        if ([aCon.requestName isEqualToString:CLOSEST_STUDENT_DETAILS])
        {
            
            self.appDelegate.closestStudentDetails = [aCon.responseString objectFromJSONString];
            
            NSLog(@">>>>>>>>>  %@",self.appDelegate.closestStudentDetails);

        }
        
        
    }
    if([self.appDelegate.closestStudentDetails  count]>0)
    {
    [self.studentArray addObject:[[self.appDelegate.closestStudentDetails objectAtIndex:0] valueForKey:@"FullName"]];

    [self setStudentData];

    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Message" message:@"No data available" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
    }
}


#pragma mark - Set Student data

-(void) setStudentData
{
    NSLog(@"DATA >>>>>>  %@ %@",[[self.appDelegate.closestStudentDetails objectAtIndex:0] valueForKey:@"SurName"],[[self.appDelegate.closestStudentDetails objectAtIndex:0] valueForKey:@"UDID"]);
    
    [self.studentDetailsDictionary removeAllObjects];
    
    [self.studentDetailsDictionary setValue:[NSString stringWithFormat:@"%@",[[self.appDelegate.closestStudentDetails objectAtIndex:0] valueForKey:@"SurName"] ] forKey:@"SurName"];
    
    [self.studentDetailsDictionary setValue:[[self.appDelegate.closestStudentDetails objectAtIndex:0] valueForKey:@"KnownAsName"] forKey:@"KnownAsName"];
    
    [self.studentDetailsDictionary setValue:[[[[self.appDelegate.closestStudentDetails objectAtIndex:0] valueForKey:@"StudentContacts"] objectAtIndex:3] valueForKey:@"Email"] forKey:@"Email"];
    
    [self.studentDetailsDictionary setValue:[[self.appDelegate.closestStudentDetails objectAtIndex:0] valueForKey:@"HomeTeacher"] forKey:@"Home Teacher"];
    
    [self.studentDetailsDictionary setValue:[[self.appDelegate.closestStudentDetails objectAtIndex:0] valueForKey:@"HomeRoom"] forKey:@"Home Room"];
    
    [self.studentDetailsDictionary setValue:[[self.appDelegate.closestStudentDetails objectAtIndex:0] valueForKey:@"House"] forKey:@"House"];
    
    [self.studentDetailsDictionary setValue:[[self.appDelegate.closestStudentDetails objectAtIndex:0] valueForKey:@"Dean"] forKey:@"Dean"];
    
    [self.studentDetailsDictionary setValue:[[self.appDelegate.closestStudentDetails objectAtIndex:0] valueForKey:@"StudentAlert"] forKey:@"StudentAlert"];
  //   [self.studentDetailsDictionary setValue:[NSString stringWithFormat:@"%@",[[self.appDelegate.closestStudentDetails objectAtIndex:0] valueForKey:@"UDID"] ] forKey:@"StudentAlert"];
    
    [self.rightPanelStudentImageView setImageWithURL:[NSURL URLWithString:[[NSString stringWithFormat:@"%@Students/GetStudentImageByName/%@",BASE_URL,[self.appDelegate.arrayForStudentDetails valueForKey:@"MemberCode"]] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] placeholderImage:[UIImage imageNamed:@"no-imageBig.png"]];
    
    [self.rightPanelTableView reloadData];
    [self.leftPanelTableView reloadData];
    
    [self startAdvertising];

}


#pragma mark - Button Action

- (IBAction)proximityButtonAction:(id)sender
{
    UIButton *btn = (UIButton *)sender;
    
    int selectedIndex = btn.selected ? 0 : 1;
        
    btn.selected = selectedIndex;
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - Bluetooth Related Methods

-(void)startAdvertising
{
    manager = [[CBPeripheralManager alloc]initWithDelegate:self queue:nil];
}
-(BOOL)supportBTLE
{

    NSString * state = nil;
    
    switch ([manager state])
    {
        case CBCentralManagerStateUnsupported:
            state = @"The platform/hardware doesn't support Bluetooth Low Energy.";
            break;
        case CBCentralManagerStateUnauthorized:
            state = @"The app is not authorized to use Bluetooth Low Energy.";
            break;
        case CBCentralManagerStatePoweredOff:
            state = @"Bluetooth is currently powered off.";
            break;
        case CBCentralManagerStatePoweredOn:
            return TRUE;
        case CBCentralManagerStateUnknown:
        default:
            return false;
    }
    UIAlertView *alv=[[UIAlertView alloc] initWithTitle:@"Message" message:state delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alv show];
    [alv release];
    
    return FALSE;

}
- (void)centralManagerDidUpdateState:(CBCentralManager *)central{
    if ([self supportBTLE])
    {
        
        switch (central.state) {
            case CBCentralManagerStatePoweredOn:
                [centmanager scanForPeripheralsWithServices:nil options:@{ CBCentralManagerScanOptionAllowDuplicatesKey : [NSNumber numberWithBool:YES] }];
                break;
                
            default:
                NSLog(@"%i",central.state);
                break;
        }
    }
    else
    {
    
    }
    
}

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)aPeripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI {
    if ([RSSI floatValue]>=-45.f) {
        NSLog(@"Greater than 45");
        [central stopScan];
        aCperipheral = aPeripheral;
        [central connectPeripheral:aCperipheral options:nil];
    }
}

- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
    NSLog(@"Failed:%@",error);
}

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)aPeripheral
{
    NSLog(@"Connected:%@",aPeripheral.UUID);
    [aCperipheral setDelegate:self];
    [aCperipheral discoverServices:nil];
}

- (void)peripheral:(CBPeripheral *)aPeripheral didDiscoverServices:(NSError *)error {
    for (CBService *aService in aPeripheral.services){
        if ([aService.UUID isEqual:[CBUUID UUIDWithString:@"EBA38950-0D9B-4DBA-B0DF-BC7196DD44FC"]]) {
            [aPeripheral discoverCharacteristics:nil forService:aService];
        }
    }
}

-(void)peripheral:(CBPeripheral *)aPeripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
    for (CBCharacteristic *aChar in service.characteristics){
        NSLog(@"%@",aChar.UUID);
        
        if ([aChar.UUID isEqual:[CBUUID UUIDWithString:@"DA17"]]) {
            //NSLog(@"Find DA17");
            NSString *mainString = [NSString stringWithFormat:@"DA12312"];
            NSData *mainData1= [mainString dataUsingEncoding:NSUTF8StringEncoding];
            [aPeripheral writeValue:mainData1 forCharacteristic:aChar type:CBCharacteristicWriteWithResponse];
        }
    }
}

- (void)peripheral:(CBPeripheral *)aPeripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
    [centmanager cancelPeripheralConnection:aPeripheral];
}

- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral
{
    NSLog(@"Done");
    if ([self supportBTLE])
    {
    
   
    switch (peripheral.state) {
        case CBPeripheralManagerStatePoweredOn:{
            CBUUID *cUDID = [CBUUID UUIDWithString:@"DA18"];
            CBUUID *cUDID1 = [CBUUID UUIDWithString:@"DA17"];
            CBUUID *cUDID2 = [CBUUID UUIDWithString:@"DA16"];
            if([self.appDelegate.closestStudentDetails count]>0)
            {
                CBUUID *sUDID =[CBUUID UUIDWithString:[[self.appDelegate.closestStudentDetails objectAtIndex:0] valueForKey:@"UDID"]];//[CBUUID UUIDWithString:@"EBA38950-0D9B-4DBA-B0DF-BC7196DD44FD"];//]; ////FBF566A1-F789-4C30-BDB5-70E2756E5D19
           
           characteristic = [[CBMutableCharacteristic alloc]initWithType:cUDID properties:CBCharacteristicPropertyNotify value:nil permissions:CBAttributePermissionsReadable];
            characteristic1 = [[CBMutableCharacteristic alloc]initWithType:cUDID1 properties:CBCharacteristicPropertyWrite value:nil permissions:CBAttributePermissionsWriteable];
            characteristic2 = [[CBMutableCharacteristic alloc]initWithType:cUDID2 properties:CBCharacteristicPropertyRead value:nil permissions:CBAttributePermissionsReadable];
           // NSLog(@"[[self.appDelegate.closestStudentDetails objectAtIndex:0] valueForKey %@",[[self.appDelegate.closestStudentDetails objectAtIndex:0] valueForKey:@"UDID"]);
            servicea = [[CBMutableService alloc]initWithType:sUDID primary:YES];
            servicea.characteristics = @[characteristic,characteristic1,characteristic2];
            [peripheral addService:servicea];
            }
        }
            break;
            
        default:
            NSLog(@"%i",peripheral.state);
            break;
    }
    }
}
-(NSString *)getUUID
{
    CFUUIDRef newUniqueId = CFUUIDCreate(kCFAllocatorDefault);
    NSString * uuidString = ( NSString*)CFUUIDCreateString(kCFAllocatorDefault, newUniqueId);
    CFRelease(newUniqueId);
    
    return uuidString;
}
- (void)peripheralManager:(CBPeripheralManager *)peripheral didAddService:(CBService *)service error:(NSError *)error{
    NSLog(@"Added");
    int strID= [[[self.appDelegate.closestStudentDetails objectAtIndex:0] valueForKey:@"StudentId"] intValue];
    NSDictionary *advertisingData = @{CBAdvertisementDataLocalNameKey : [NSString stringWithFormat:@"%d",strID ] , CBAdvertisementDataServiceUUIDsKey : @[[CBUUID UUIDWithString:[[self.appDelegate.closestStudentDetails objectAtIndex:0] valueForKey:@"UDID"]]]};
    
    
    
    // //EBA38950-0D9B-4DBA-B0DF-BC7196DD44FD
    
    [peripheral startAdvertising:advertisingData];
    
  //  [NSTimer scheduledTimerWithTimeInterval:2.0 target:peripheral selector:@selector(startAdvertising:) userInfo: nil repeats:YES];
}

- (void)peripheralManagerDidStartAdvertising:(CBPeripheralManager *)peripheral error:(NSError *)error{
    NSLog(@"Hahah");
    int strID= [[[self.appDelegate.closestStudentDetails objectAtIndex:0] valueForKey:@"StudentId"] intValue];
    NSDictionary *advertisingData = @{CBAdvertisementDataLocalNameKey : [NSString stringWithFormat:@"%d",strID ] , CBAdvertisementDataServiceUUIDsKey : @[[CBUUID UUIDWithString:[[self.appDelegate.closestStudentDetails objectAtIndex:0] valueForKey:@"UDID"]]]};
    [peripheral startAdvertising:advertisingData];

}

- (void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didSubscribeToCharacteristic:(CBCharacteristic *)characteristic12{
    NSLog(@"Core:%@",characteristic12.UUID);
    NSLog(@"Connected");
    [self writeData:peripheral];
}

- (void)writeData:(CBPeripheralManager *)peripheral{
    NSDictionary *dict = @{ @"NAME" : @"Khaos Tian",@"EMAIL":@"khaos.tian@gmail.com" };
    mainData = [NSJSONSerialization dataWithJSONObject:dict options:kNilOptions error:nil];
    while ([self hasData]) {
        if([peripheral updateValue:[self getNextData] forCharacteristic:characteristic onSubscribedCentrals:nil]){
            [self ridData];
        }else{
            return;
        }
    }
    NSString *stra = @"ENDAL";
    NSData *dataa = [stra dataUsingEncoding:NSUTF8StringEncoding];
    [peripheral updateValue:dataa forCharacteristic:characteristic onSubscribedCentrals:nil];
}

- (void)peripheralManagerIsReadyToUpdateSubscribers:(CBPeripheralManager *)peripheral{
    while ([self hasData]) {
        if([peripheral updateValue:[self getNextData] forCharacteristic:characteristic onSubscribedCentrals:nil]){
            [self ridData];
        }else{
            return;
        }
    }
    NSString *stra = @"ENDAL";
    NSData *dataa = [stra dataUsingEncoding:NSUTF8StringEncoding];
    [peripheral updateValue:dataa forCharacteristic:characteristic onSubscribedCentrals:nil];
}

- (BOOL)hasData{
    if ([mainData length]>0) {
        return YES;
    }else{
        return NO;
    }
}

- (void)ridData{
    if ([mainData length]>19) {
        mainData = [mainData subdataWithRange:NSRangeFromString(range)];
    }else{
        mainData = nil;
    }
}

-(NSData *)getNextData
{
    NSData *data;
    if ([mainData length]>19) {
        int datarest = [mainData length]-20;
        data = [mainData subdataWithRange:NSRangeFromString(@"{0,20}")];
        range = [NSString stringWithFormat:@"{20,%i}",datarest];
    }else{
        int datarest = [mainData length];
        range = [NSString stringWithFormat:@"{0,%i}",datarest];
        data = [mainData subdataWithRange:NSRangeFromString(range)];
    }
    return data;
}

- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveReadRequest:(CBATTRequest *)request{
    NSString *mainString = [NSString stringWithFormat:@"GN123"];
    NSData *cmainData= [mainString dataUsingEncoding:NSUTF8StringEncoding];
    request.value = cmainData;
    [peripheral respondToRequest:request withResult:CBATTErrorSuccess];
}

- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveWriteRequests:(NSArray *)requests{
    for (CBATTRequest *aReq in requests){
        //NSLog(@"%@",[[NSString alloc]initWithData:aReq.value encoding:NSUTF8StringEncoding]);
        [peripheral respondToRequest:aReq withResult:CBATTErrorSuccess];
    }
}

- (void)willEnterBackgroud{
    [manager stopAdvertising];
    [centmanager stopScan];
}

- (void)willBacktoForeground{
    NSDictionary *advertisingData = @{CBAdvertisementDataServiceUUIDsKey : @[[CBUUID UUIDWithString:[[self.appDelegate.closestStudentDetails objectAtIndex:0] valueForKey:@"UDID"]]]};
    [manager startAdvertising:advertisingData];
    [centmanager scanForPeripheralsWithServices:nil options:nil];
}

- (void)dealloc {
    [_baseImageView release];
    [_rightPanelImageView release];
    [_leftPanelView release];
    [_leftPanelImageView release];
    [_leftPanelTableView release];
    [_searchBarImgView release];
    [_searchBarTextField release];
    [_proximityButton release];
    [_searchBarLeftimageView release];
    [_rightPanelTableView release];
    [_rightPanelheaderImageView release];
    [_studentDetailsDictionary release];
    [_rightPanelStudentImageView release];
    [_rightPanelGraphView release];
    [_studentDetailsArray4Leftpart release];
    [super dealloc];
}

@end
